package com.cn.pack.controller;

import com.cn.pack.config.HystrixThreadLocal;
import com.cn.pack.service.ThreadContextService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

@RestController
public class ThreadContextController {

    @Autowired
    private ThreadContextService threadContextService;

    @RequestMapping(path = "/user/get")
    public String getUser(@RequestParam("id") String id) {
        HystrixThreadLocal.threadLocal.set("userId=" + id);

        RequestContextHolder.currentRequestAttributes().setAttribute("userId", "userId=" + id, RequestAttributes.SCOPE_REQUEST);

        System.out.println("---------------- current thread : " + Thread.currentThread().getId());
        System.out.println("---------------- thread local: " + HystrixThreadLocal.threadLocal.get());
        System.out.println("---------------- requestContextHolder : " + RequestContextHolder.currentRequestAttributes().getAttribute("userId", RequestAttributes.SCOPE_REQUEST));

        System.out.println("*****************************");
        String user = threadContextService.getUser(id);
        System.out.println("*****************************");

        System.out.println("------------------ user = " + user);
        return user;
    }
}
